<template>
    <div class="right-content">
      <div class="schedule">
        <!-- 大日历表 -->
        <div class="right">
          <full-calendar
            ref="Fullcalendar"
            style="height: 100%"
            :options="calendarOptions"
          >
          </full-calendar>
          <!-- 新建日程弹窗 start -->
          <el-dialog
            :title="ScheduleForm.id ? '编辑日程' : '新建日程'"
            :visible.sync="dialogVisible"
            :close-on-click-modal="false"
            top="30px"
            width="50%"
          >
            <el-form
              :model="ScheduleForm"
              ref="ScheduleForm"
              label-width="120px"
              class="schedule-form"
            >
              <el-form-item prop="title" label="日程标题" style="width:98%">
                <el-input
                  type="text"
                  v-model="ScheduleForm.title"
                  placeholder="添加日程、会议、活动等标题"
                  class="Scheduleel-input"
                  :disabled="Disable"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="alldaySwitch" label="全天">
                <el-switch
                  v-model="ScheduleForm.alldaySwitch"
                  @change="changeSwitch(ScheduleForm.alldaySwitch)"
                >
                </el-switch>
              </el-form-item>
              <!-- 时间选择 -->
              <el-form-item v-if="ScheduleForm.alldaySwitch == true" label="进行时间">
                <el-col :span="3">
                  <el-form-item prop="startDate">
                    <el-date-picker
                      v-model="ScheduleForm.startDate"
                      type="date"
                      placeholder="开始日期"
                    >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="3" :offset="5">
                  <el-form-item prop="endDate">
                    <el-date-picker
                      v-model="ScheduleForm.endDate"
                      type="date"
                      placeholder="结束日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <el-form-item v-else label="进行时间">
                <el-col :span="3">
                  <el-form-item prop="startDate">
                    <el-date-picker
                      v-model="ScheduleForm.startDate"
                      type="date"
                      placeholder="开始日期">
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="3" :offset="5">
                  <el-form-item prop="startTime">
                    <el-time-picker
                      v-model="ScheduleForm.startTime"
                      :picker-options="{
                        selectableRange: '09:00:00 - 17:00:00'
                      }"
                      placeholder="开始时间">
                    </el-time-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="3" :offset="5">
                  <el-form-item prop="endTime">
                    <el-time-picker
                      v-model="ScheduleForm.endTime"
                      :picker-options="{
                        selectableRange: '09:00:00 - 17:00:00'
                      }"
                      placeholder="结束时间">
                    </el-time-picker>
                  </el-form-item>
                </el-col>
              </el-form-item>
              <!-- 参与人员 -->
              <el-form-item label="参与人员">
                <div
                  style="width:98%;height:5vh;display:flex;justify-content:space-between;overflow:hidden"
                >
                  <el-button
                    @click="openaddpar()"
                    style="width: 5vw; height: 40px; color: #C0C4CC;"
                    :disabled="Disable"
                  >
                    新增
                  </el-button>
                  <div
                    style="backgroundColor:#F5F7FA;width:85%;height:4.7vh;overflow-x:auto"
                  >
                    <el-button
                    style="height:4.5vh"
                      v-for="item in ScheduleForm.participants"
                      :key="item.id"
                    >
                      {{item.name}}
                    </el-button>
                  </div>
                </div>
              </el-form-item>
              <el-form-item prop="address" label="地点">
                <el-input
                  type="text"
                  v-model="ScheduleForm.address"
                  placeholder="添加地点或会议室"
                  :disabled="Disable"
                >
                </el-input>
              </el-form-item>
              <el-form-item prop="color" label="紧急程度">
              <el-select v-model="ScheduleForm.color" :disabled="Disable">
                <el-option label="紧急日程" :value="0"></el-option>
                <el-option label="一般日程" :value="1"></el-option>
                <el-option label="过期日程" :value="2"></el-option>
              </el-select>
            </el-form-item>
              <el-form-item prop="remark" label="备注">
                <el-input
                  type="textarea"
                  :rows="3"
                  placeholder="请输入内容"
                  v-model="ScheduleForm.remark"
                  :disabled="Disable">
                </el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" @click="delSchedule(ScheduleForm)" v-if="ScheduleForm.id && Disable === true">删除</el-button>
              <el-button type="primary" @click="editdialog" v-if="ScheduleForm.id && Disable === true">编辑</el-button>
              <el-button type="primary" @click="dialogVisible = false" v-else-if="ScheduleForm.id && Disable === false">确定</el-button>
              <el-button type="primary" @click="submitScheduleForm(ScheduleForm)" v-else>新建</el-button>
            </span>
          </el-dialog>
          <!-- 新建日程弹窗 end -->
        </div>
      </div>
      <!-- 新增参与者弹窗 start -->
      <el-dialog
        :visible.sync="addpardialogVisible"
        :close-on-click-modal="false"
        top="20px"
        width="40%"
        style="height: 800px; overflow-y: hidden"
        class="addpar"
      >
        <el-input
          type="text"
          v-model="search_pro"
          suffix-icon="el-icon-search"
          placeholder="请输入查询姓名"
          @keyup.enter.native="queryParticipant"
        >
        </el-input>
        <div class="BTN">
          <el-button
            icon="el-icon-close"
            v-for="(item, index) in participateEmp"
            :key="item.id"
            @click="deleteems(index)"
          >
            {{item.name}}
          </el-button>
        </div>
        <div class="cards">
          <el-card
            v-for="(item, index) in emsList"
            :key="index"
            style="margin-top: 10px"
            :body-style="{width: '96%', display: 'flex', justifyContent: 'space-between', padding: '5px'}"
            @click.native="addems(item)"
          >
            <div class="left">
              <el-avatar shape="square" :size="60" :src="item.header"></el-avatar>
            </div>
            <div class="right">
              <span class="right-left">
                {{item.name}}
                <p style="height: 5px"></p>
                {{item.address}}
              </span>
              <span class="right-right">
                职位：{{item.position.name}}
                <p style="height: 5px"></p>
                部门：{{item.department.name}}
              </span>
            </div>
          </el-card>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="canceladd()">取消</el-button>
          <el-button type="primary" @click="confirmadd()">确定</el-button>
        </span>
      </el-dialog>
      <!-- 新增参与者弹窗 end -->
    </div>
</template>

<script>
// 引入日历组件
import '@fullcalendar/core/vdom'
import FullCalendar from '@fullcalendar/vue'
import dayGridPlugin from '@fullcalendar/daygrid'
import interactionPlugin from '@fullcalendar/interaction'
import timeGridePlugin from '@fullcalendar/timegrid'

import { copy } from '../../utils/common'

export default {
  name: 'Month1',
  data() {
    return {
      search_schedule: '', // 日程搜索框
      value: new Date(),
      // 设置日历的一些配置及属性
      calendarOptions: {
        // eslint-disable-next-line no-undef
        timeGridePlugin, // 可显示每日的时间段
        height: 620,
        // aspectRatio: '2.2',
        allDaySlot: false,
        plugins: [dayGridPlugin, interactionPlugin, timeGridePlugin], // 时间控件
        headerToolbar: {
          left: 'today prev,next',
          center: 'title',
          right: 'dayGridMonth,dayGridWeek,dayGrid'
        },
        buttonText: {
          // 设置按钮
          today: '今天',
          month: '月',
          week: '周',
          dayGrid: '天'
        },
        title: 'YYYY MM DD',
        firstDay: 0,
        weekNumberCalculation: 'ISO', // 周数
        // allDaySlot: true, // 是否设置显示全天
        editable: true, // 事件是否可编辑
        selectable: true,
        navLinks: true,
        // displayEventEnd: true, // 所有视图显示结束时间
        defaultView: 'month', // 设置默认显示月，可选周、日
        weekNumbers: false, // 显示周数
        dateClick: this.handleDateClick,
        eventClick: this.handleEventClick,
        eventsSet: this.handleEvents,
        select: this.handleDateSelect,
        events: [], // 储存将要渲染在日历上的日程
        // eventColor: '#f08f00', // 修改日程背景色
        locale: 'zh-cn', // 设置语言
        // customButtons: {}
        eventLimit: true, // 限制每天显示的条数
        eventLimitClick: 'week',
        dayMaxEvents: true
      },
      dialogVisible: false, // 新增日程弹框
      ScheduleForm: { // 储存日程表单弹窗新建的数据或者是将要完全渲染在日程弹窗上的数据
        id: '',
        title: '',
        alldaySwitch: true,
        startDate: '',
        startTime: '',
        endDate: '',
        endTime: '',
        address: '',
        color: '',
        eIds: [],
        participants: [],
        remark: ''
      },
      rules: [],
      scheduledata: [],
      Disable: false,
      search_data: '',
      search_pro: '', // 参与者搜索框
      addpardialogVisible: false, // 新增参与者弹窗
      participateEmp: [], // 新增参与者弹窗操作的参与者数组
      emsList: [] // 新增参与者弹窗 获取的员工信息数组
    }
  },
  components: {
    // eslint-disable-next-line no-unused-expressions
    FullCalendar
  },
  mounted() {
    this.getscheduledata()
    this.getemsList()
  },
  methods: {
    // 获取准确查询后的参与者信息
    queryParticipant() {
      var page = 1
      var size = 10
      var url = '/admin/emp/?currentPage=' + page + '&size=' + size
      if (this.search_pro) {
        url = url + '&name=' + this.search_pro
        this.getRequest(url).then(resp => {
          this.emsList = resp.data
          console.log(this.emsList)
        })
      } else {
        this.$message.error('请输入查询名字')
      }
    },
    // 确定添加
    confirmadd() {
      this.addpardialogVisible = false
      this.ScheduleForm.participants = copy(this.participateEmp)
    },
    // 取消添加
    canceladd() {
      this.addpardialogVisible = false
    },
    // 将选中的参与者添加进participateEmp
    addems(item) {
      var len = this.participateEmp.length
      var count = 0
      for (var i = 0; i < len; i++) {
        if (this.participateEmp[i].id === item.id && this.participateEmp[i].name === item.name) break
        else count++
      }
      // 说明前面无相同数据
      if (count === len) {
        this.participateEmp.push({
          id: item.id,
          name: item.name
        })
      }
    },
    // 获取员工数据传入emsList
    getemsList() {
      var page = 1
      var size = 10
      this.getRequest(`admin/emp/${page}/${size}`).then(resp => {
        if (resp) {
          this.emsList = resp.list
        }
      })
    },
    // 取消参与者，从participateEmp中移除
    deleteems(index) {
      this.participateEmp.splice(index, 1)
    },
    // 打开新增参与者弹框
    openaddpar() {
      this.addpardialogVisible = true
      this.participateEmp = copy(this.ScheduleForm.participants)
      // this.getemsList()
    },
    // 获取后端传送的日程数据
    getscheduledata() {
      this.getRequest('/schedule/').then(resp => {
        if (resp) {
          this.scheduledata = resp.data
          this.ConverseScheduledata(this.scheduledata)
        } else {
          console.log('返回数据不存在')
        }
      }, error => console.error(error))
    },

    // 获取日程事件title xx:xx~xx:xx title
    getTitle(startdate, enddate) {
      const start = startdate.substring(11, 16)
      const end = enddate.substring(11, 16)
      if (start === '09:00' && end === '17:00') {
        return ''
      } else {
        return `${start}~${end}`
      }
    },
    // 处理日期格式 XXXX-XX-XX
    dealWithTime(date) {
      var newDate = /\d{4}-\d{1,2}-\d{1,2}/g.exec(date)[0]
      return newDate
    },
    // 转换格式 后端color [0,1,2] => 前端颜色
    getColor(color) {
      if (color === 0) {
        return '#F56C6C'
      } else if (color === 1) {
        return 'rgba(64,158,255)'
      } else {
        return '#909399'
      }
    },
    // 转换格式，后端格式 => 前端calendarOptions.event格式
    ConverseScheduledata(scheduledata) {
      var newArr = []
      scheduledata.forEach((item, index) => {
        newArr.push({
          id: index + 1,
          title: `${this.getTitle(item.startTime, item.endTime)} ${item.title}`,
          start: this.dealWithTime(item.startTime),
          end: this.dealWithTime(item.endTime),
          color: `${this.getColor(item.color)}`
        })
      })
      this.calendarOptions.events = newArr
      // console.log('this.calendarOptions.events', this.calendarOptions.events)
    },
    // 转换格式，后端scheduledata[index].participants => 前端ScheduleForm.participants
    // Participants(participants) {
    //   var newParticipants = ''
    //   participants.forEach((item, index) => {
    //     if (index !== participants.length - 1) {
    //       newParticipants = newParticipants + item.name + '，'
    //     } else {
    //       newParticipants = newParticipants + item.name
    //     }
    //   })
    //   return newParticipants
    // },
    // 转换格式， 后端scheduledata[index].color 数字 => 前端ScheduleForm.color 程度
    ConverseColor(color) {
      if (color === 0) {
        return '紧急事件'
      } else if (color === 1) {
        return '一般事件'
      } else {
        return '过期事件'
      }
    },
    // 初始化弹窗，后端格式 => 前端ScheduleForm格式
    initDialog(id) {
      this.scheduledata.forEach((item, index) => {
        if ((index + 1) === Number(id)) {
          this.ScheduleForm = {
            id: index + 1,
            sid: item.sid,
            title: item.title,
            alldaySwitch: item.allDaySwitch,
            startDate: item.startTime.substring(0, 10),
            startTime: item.startTime.substring(11, 19),
            endDate: item.endTime.substring(0, 10),
            endTime: item.endTime.substring(11, 16),
            address: item.address,
            remark: item.remark,
            color: `${this.ConverseColor(item.color)}`,
            // participants: `${this.Participants(item.participants)}`
            participants: item.participants,
            eIds: item.eIds
          }
        }
      })
    },
    // 转换格式，ScheduleForm.participants[index].id => eIds[index]
    ConverseeIds(participants) {
      var eids = []
      participants.forEach((item) => {
        eids.push(item.id)
      })
      return eids
    },
    // 转换格式，前端ScheduleForm => 后端scheduledata[index]
    ConverseScheduleForm(form) {
      var newForm = {}
      newForm = {
        title: form.title,
        allDaySwitch: Number(form.alldaySwitch),
        startTime: `${this.getTHMS(form.startDate, form.endDate, form.startTime, form.endTime, 0)}`,
        endTime: `${this.getTHMS(form.startDate, form.endDate, form.startTime, form.endTime, 1)}`,
        address: form.address,
        remark: form.remark,
        color: Number(form.color),
        eIds: this.ConverseeIds(form.participants)
      }
      return newForm
    },
    // 点击日期，显示新增
    handleDateClick(date) {
      this.$forceUpdate() // 强制刷新页面
      // console.log('点击的日历日期：', date)
      this.dialogVisible = true
      this.Disable = false
      this.ScheduleForm = {
        id: '', // 事件ID
        title: '',
        alldaySwitch: true, // 全天按钮开关
        startDate: '', // 日期
        startTime: '', // 时间
        endDate: '',
        endTime: '',
        participants: [], // 参与者（不要全部信息，我这边手动填入，相当于一个参与者的数组传给你）
        address: '', // 日程地点
        remark: '', // 备注
        color: '',
        eIds: []
      }
    },
    // 点击日程事件，显示详情
    handleEventClick(calEvent) {
      this.Disable = true
      // console.log('点击的日程事件：', calEvent.event._def.publicId)
      this.dialogVisible = true
      this.initDialog(calEvent.event._def.publicId)
    },
    // 点击日程事件，跳转每日日程
    handleEvents(events) {
      // console.log('点击的事件跳转：', events)
    },
    handleDateSelect(selectInfo) {
      // console.log('事件4：', selectInfo)
    },
    // 提交日程数据
    submitScheduleForm(scheduleform) {
      var form = this.ConverseScheduleForm(scheduleform)
      this.$refs.ScheduleForm.validate(valid => {
        if (valid) {
          this.postRequest('/schedule/', form).then(resp => {
            if (resp) {
              this.dialogVisible = false
              this.getscheduledata()
              this.$forceUpdate()
            }
          }, error => console.log(error))
        }
      })
    },
    // 转换格式 yyyy-mm-dd
    getTime(date) {
      var newdate = new Date(date)
      var y = newdate.getFullYear()
      var m = newdate.getMonth() + 1
      m = m < 10 ? ('0' + m) : m
      var d = newdate.getDate()
      d = d < 10 ? ('0' + d) : d
      return (y + '-' + m + '-' + d)
    },
    // 转换格式 hh:MM:SS
    getHMS(date) {
      console.log(date)
      var newdate = new Date(date)
      var h = newdate.getHours()
      h = h < 10 ? ('0' + h) : h
      var M = newdate.getMinutes()
      M = M < 10 ? ('0' + M) : M
      var S = newdate.getSeconds()
      S = S < 10 ? ('0' + S) : S
      return (h + ':' + M + ':' + S)
    },
    // 转换格式 yyyy-mm-dd hh:MM:SS
    getTHMS(startDate, endDate, startTime, endTime, status) {
      console.log(endDate)
      // 0 为开始时间
      if (status === 0) {
        // 不全天
        if (endDate === '') {
          return `${this.getTime(startDate)} ${this.getHMS(startTime)}`
        } else { // 全天
          return `${this.getTime(startDate)} 09:00:00`
        }
      } else { // 1 为结束时间
        // 不全天
        if (endDate === '') {
          return `${this.getTime(startDate)} ${this.getHMS(endTime)}`
        } else { // 全天
          return `${this.getTime(endDate)} 17:00:00`
        }
      }
    },
    // 编辑弹窗
    editdialog() {
      this.Disable = false
    },
    // 删除日程
    delSchedule(scheduleform) {
      this.$confirm(`请确定是否删除${scheduleform.title}待办`, '提示', {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteRequest('/schedule/' + scheduleform.sid).then(resp => {
          if (resp) {
            this.dialogVisible = false
            this.getscheduledata()
            this.$forceUpdate()
          } else {
            console.log('error')
          }
        }, error => { console.log(error) })
      }).catch(() => {
        this.$message.info('已取消删除')
        this.dialogVisible = false
        this.getscheduledata()
        this.$forceUpdate()
      })
    },
    // 改变开关状态
    changeSwitch(data) {
      this.ScheduleForm.alldaySwitch = data
    }
  }
}
</script>

<style>
@import '../../assets/css/form.css';
/** 按钮 */
.fc .fc-button {
  background-color: rgba(64,158,255);
  border: none;
}
/** 鼠标悬浮的时候的按钮样式 */
.fc .fc-button:hover {
  background-color: rgba(131,192,255);
}
.fc .fc-button-primary:not(:disabled).fc-button-active {
  background-color: rgba(64,158,255);
  border: none;
}
/** 今天按钮 */
.fc .fc-button-primary:disabled {
  background-color: rgba(64,158,255);
}
/**=============================== 新增参与者 start ================================*/
.addpar .cards {
  width: 96%;
  height: 400px;
  height: 50vh;
  overflow-y: auto;
}
.addpar .cards::-webkit-scrollbar {
  display: none;
}
.addpar .el-card:hover {
  cursor: pointer;
  width: 97%;
  height: 72px;
  background-color: rgba(236,245,255);
}
.addpar .left {
  display: inline-block;
  width: 60px;
  height: 60px;
}
.addpar .right {
  display: inline-block;
  display: flex;
  width: 100%;
  height: 50px;
  padding: 5px;
  font-size: 18px;
}
.addpar .right-left {
  display: inline-block;
  width: 500px;
  height: 50px;
}
.addpar .right-right {
  display: inline-block;
  width: 100%;
  height: 50px;
  text-align: center;
}
.addpar .BTN {
  width: 100%;
  height: 10vh;
  overflow-y: auto;
}
.addpar .BTN .el-button {
  width: 6vw;
  height: 5vh;
  margin-top: 1vh;
  margin-left: 0px;
  margin-right: 10px;
}
</style>
